
var Web3 = require("../node_modules/web3");
var contract = require("../node_modules/truffle-contract");
var metacoin_artifacts = require("../build/contracts/MetaCoin.json");

var App = function() {

    var MetaCoin = contract(metacoin_artifacts);

    var accounts;
    var account;
    var web3js;

    this.init = function() {
        var self = this;
        if (typeof web3js !== 'undefined') {
            web3js = new Web3(web3.currentProvider);
            console.log(">>>web3 =", web3);
        } else {
            web3js = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:9545"));
            console.log(">>>on load>>>web3 =", web3js); 
        }

        MetaCoin.setProvider(web3js.currentProvider);
        web3js.eth.getAccounts(function(err, accs) {
            if (err != null) {
                alert("There was an error fetching your accounts.");
                return;
            }
      
            if (accs.length == 0) {
                alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
                return;
            }
      
            accounts = accs;
            account = accounts[0];
      
            self.refreshBalance();
            var balance = web3js.eth.getBalance(account);
            console.log(balance.valueOf()); // instanceof BigNumber
        });
    };


    this.refreshBalance = function() {
        var self = this;
        console.log(">>>refreshBalance>>")
        var meta;
        MetaCoin.deployed().then(function(instance) {
            meta = instance;
            return meta.getBalance.call(account, {from: account});
        }).then(function(value) {
            var balance_element = document.getElementById("balance");
            balance_element.innerHTML = value.valueOf();
            var balance = web3js.eth.getBalance(account);
            console.log(balance.valueOf()); // instanceof BigNumber
        }).catch(function(e) {
            console.log(e);
            // self.setStatus("Error getting balance; see log.");
        });
    };
}

module.exports = App;